import  requests
import time
import  re

# todo js功能 字符串转变为url的参数
def  gettk(e):
      i = 5381
      n=len(e)
      for t in range(n):
            i += (i << 5) + ord(e[t])
      return str(2147483647 & i)


# todo 把cookie转化成字典
def string2dic(str):
    li =str.split(';')
    cookie_dict={}
    for i in li:
        if len(i)>2:
         cookie_dict[i.split('=')[0].strip()] = i.split('=')[1].strip()
    return cookie_dict

# todo 把字典转换成cookie 字符串
def dict2string(cookie_dict):
    cookie_str=''
    for key in cookie_dict:
        cookie_str+=key+'='+cookie_dict[key]+'; '
    return cookie_str

# todo 新的cookie字典更新老的cookie字典
def updatecookie(old,new):
    for key in new:
        old[key]=new[key]



# todo 主要功能，返回更新后的登入信息
# return login_message  字典
def updaelogin():
    file = open('cookie.txt','r',encoding='utf-8')
    cookie = file.read()
    file.close()
    old_cookie_dict =string2dic(cookie)

    # *********************************************
    # todo url参数
    g_vstk=gettk(old_cookie_dict['vusession'])
    g_actk=gettk(old_cookie_dict['access_token'])
    s=int(str(time.time()).replace('.','')[0:13])
    p=s+1                                                                                                                                         # g_vstk=1744815838&g_actk=404856544
    # ***********************************************
    url="https://access.video.qq.com/user/auth_refresh?vappid=11059694&vsecret=fdf61a6be0aad57132bc5cdf78ac30145b6cd2c1470b0cfe&type=wx&g_tk=&g_vstk="+g_vstk+"&g_actk="+g_actk+"&callback=jQuery191027536418242202965_"+str(s)+"&_="+str(p)
    headers={
        'Referer':'https://v.qq.com/',
        'Cookie':cookie
    }
    r=requests.get(url,headers=headers)
    print(r.text)
    text=r.text
    if len(text)>200:  #说明成功返回了
        # 返回更新cookie字典
        new_cookie_dict = r.cookies.get_dict()
        # 更新cookie字典
        updatecookie(old_cookie_dict,new_cookie_dict)
        # cookie字典 转cookie字符串
        new_cookie_str =dict2string(old_cookie_dict)
        file = open('cookie.txt','w',encoding='utf-8')
        file.write(new_cookie_str)
        file.close()
    login_message =eval(re.search('(\{[\s\S]*\})',text).groups()[0])
    return login_message


































